package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.Material;
import com.example.chamberlainserver.Entry.MaterialCategory;
import com.example.chamberlainserver.Service.MaterialService;
import com.example.chamberlainserver.Vo.Request.Material.MaterialQuery;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.MaterialCategoryMapper;
import com.example.chamberlainserver.mapper.MaterialMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 物资服务实现类
 */
@Service
public class MaterialServiceImpl implements MaterialService {

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private MaterialCategoryMapper materialCategoryMapper;
    
    @Autowired
    private com.example.chamberlainserver.mapper.MaterialStockLogMapper materialStockLogMapper;

    @Override
    @Transactional
    public Material addMaterial(Material material) {
        // 验证物资信息
        validateMaterial(material);

        // 插入物资记录
        materialMapper.insertMaterial(material);

        // 返回插入后的物资信息（包含自增ID）
        return material;
    }

    @Override
    @Transactional
    public Material updateMaterial(Material material) {
        // 检查物资是否存在
        Material existingMaterial = materialMapper.getMaterialById(material.getId());
        if (existingMaterial == null) {
            throw new IllegalArgumentException("物资不存在");
        }

        // 验证物资信息
        validateMaterial(material);

        // 更新物资记录
        materialMapper.updateMaterial(material);

        // 返回更新后的物资信息
        return material;
    }

    @Override
    @Transactional
    public boolean deleteMaterial(Long id) {
        // 检查物资是否存在
        Material existingMaterial = materialMapper.getMaterialById(id);
        if (existingMaterial == null) {
            return false;
        }

        // 删除物资记录
        int rows = materialMapper.deleteMaterial(id);

        return rows > 0;
    }

    @Override
    public Material getMaterialById(Long id) {
        return materialMapper.getMaterialById(id);
    }

    @Override
    public List<Material> getAllMaterials() {
        return materialMapper.getAllMaterials();
    }

    @Override
    public List<Material> getMaterialsByCategory(Integer categoryId) {
        return materialMapper.getMaterialsByCategory(categoryId);
    }

    @Override
    public List<Material> getMaterialsByLocation(Integer locationId) {
        return materialMapper.getMaterialsByLocation(locationId);
    }

    @Override
    public List<Material> searchMaterialsByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("搜索关键字不能为空");
        }
        return materialMapper.searchMaterialsByName(name.trim());
    }

    @Override
    public List<Material> getLowStockMaterials() {
        return materialMapper.getLowStockMaterials();
    }

    @Override
    @Transactional
    public Material updateMaterialStock(Long id, Integer quantity) {
        // 检查物资是否存在
        Material existingMaterial = materialMapper.getMaterialById(id);
        if (existingMaterial == null) {
            throw new IllegalArgumentException("物资不存在");
        }

        // 验证库存数量
        if (quantity < 0) {
            throw new IllegalArgumentException("库存数量不能为负数");
        }
        
        // 计算变更数量
        int beforeQuantity = existingMaterial.getQuantity();
        int changeQuantity = quantity - beforeQuantity;
        
        // 更新库存
        LocalDateTime now = LocalDateTime.now();
        materialMapper.updateMaterialStock(id, quantity, now);
        
        // 记录库存变更历史
        com.example.chamberlainserver.Entry.MaterialStockLog stockLog = new com.example.chamberlainserver.Entry.MaterialStockLog();
        stockLog.setMaterialId(id);
        stockLog.setMaterialName(existingMaterial.getMaterialName());
        stockLog.setBeforeQuantity(beforeQuantity);
        stockLog.setAfterQuantity(quantity);
        stockLog.setChangeQuantity(changeQuantity);
        stockLog.setOperationType(changeQuantity >= 0 ? "入库" : "出库");
        stockLog.setOperationReason("库存调整");
        stockLog.setOperatorName("系统管理员"); // 实际项目中应该从当前登录用户中获取
        stockLog.setOperationTime(now);
        
        materialStockLogMapper.insertStockLog(stockLog);

        // 获取更新后的物资信息
        return materialMapper.getMaterialById(id);
    }

    @Override
    @Transactional
    public Material updateInventoryTime(Long id, LocalDateTime inventoryTime) {
        // 检查物资是否存在
        Material existingMaterial = materialMapper.getMaterialById(id);
        if (existingMaterial == null) {
            throw new IllegalArgumentException("物资不存在");
        }

        // 更新盘点时间
        LocalDateTime now = LocalDateTime.now();
        materialMapper.updateInventoryTime(id, inventoryTime, now);

        // 获取更新后的物资信息
        return materialMapper.getMaterialById(id);
    }

    /**
     * 验证物资信息
     * 
     * @param material 物资信息
     */
    private void validateMaterial(Material material) {
        // 验证物资名称
        if (material.getMaterialName() == null || material.getMaterialName().trim().isEmpty()) {
            throw new IllegalArgumentException("物资名称不能为空");
        }

        // 验证分类ID
        if (material.getCategoryId() == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }

        // 检查分类是否存在
        MaterialCategory category = materialCategoryMapper.getCategoryById(material.getCategoryId());
        if (category == null) {
            throw new IllegalArgumentException("指定的分类不存在");
        }

        // 验证单位
        if (material.getUnit() == null || material.getUnit().trim().isEmpty()) {
            throw new IllegalArgumentException("单位不能为空");
        }

        // 验证库存数量
        if (material.getQuantity() == null || material.getQuantity() < 0) {
            throw new IllegalArgumentException("库存数量不能为负数");
        }

        // 验证最低库存预警值
        if (material.getMinQuantity() == null || material.getMinQuantity() < 0) {
            throw new IllegalArgumentException("最低库存预警值不能为负数");
        }

        // 验证存放位置ID
        if (material.getLocationId() == null) {
            throw new IllegalArgumentException("存放位置ID不能为空");
        }
    }
    
    @Override
    public PageResult<Material> getPagedMaterialList(MaterialQuery materialQuery) {
        // 参数校验
        if (materialQuery == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        
        // 分页参数
        Integer current = materialQuery.getCurrent();
        Integer pageSize = materialQuery.getPageSize();
        if (current == null || current < 1) {
            current = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        params.put("offset", (current - 1) * pageSize);
        params.put("limit", pageSize);
        
        // 查询条件
        if (materialQuery.getMaterialName() != null && !materialQuery.getMaterialName().trim().isEmpty()) {
            params.put("materialName", materialQuery.getMaterialName().trim());
        }
        
        if (materialQuery.getCategoryId() != null) {
            params.put("categoryId", materialQuery.getCategoryId());
        }
        
        if (materialQuery.getSpecification() != null && !materialQuery.getSpecification().trim().isEmpty()) {
            params.put("specification", materialQuery.getSpecification().trim());
        }
        
        if (materialQuery.getLocationId() != null) {
            params.put("locationId", materialQuery.getLocationId());
        }
        
        if (materialQuery.getResponsiblePerson() != null && !materialQuery.getResponsiblePerson().trim().isEmpty()) {
            params.put("responsiblePerson", materialQuery.getResponsiblePerson().trim());
        }
        
        if (materialQuery.getStatus() != null && !materialQuery.getStatus().trim().isEmpty()) {
            params.put("status", materialQuery.getStatus().trim());
        }
        
        if (materialQuery.getMinQuantity() != null) {
            params.put("minQuantity", materialQuery.getMinQuantity());
        }
        
        if (materialQuery.getMaxQuantity() != null) {
            params.put("maxQuantity", materialQuery.getMaxQuantity());
        }
        
        // 日期范围
        if (materialQuery.getStartDate() != null && !materialQuery.getStartDate().trim().isEmpty() 
                && materialQuery.getEndDate() != null && !materialQuery.getEndDate().trim().isEmpty()) {
            params.put("startDate", materialQuery.getStartDate().trim());
            params.put("endDate", materialQuery.getEndDate().trim());
        }
        
        // 查询数据
        List<Material> materials = materialMapper.getPagedMaterialList(params);
        Long total = materialMapper.getPagedMaterialCount(params);
        
        // 构建分页结果
        // 计算总页数
        Long pages = (total + pageSize - 1) / pageSize;
        PageResult<Material> pageResult = new PageResult<>(current, pageSize, total, materials);
        
        return pageResult;
    }
}